package demo;
class Money implements Cloneable{
    public double money = 12.25;
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
class Student implements Cloneable{
    public String name;
    public Money m = new Money();
    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                '}';
    }
    @Override
    protected Object clone() throws CloneNotSupportedException{
        //两次克隆都发生了向下转型
        //克隆的是Student对象，所以强转为Student类型
        //这里在Student类中创建一个student3引用，用来接收克隆后的对象的地址
        Student student3 = (Student) super.clone();//这个方法的调用只能通过super调用，发生向下转型，将Object类转化成为Student类
        //克隆了Student对象 里面的Money对象，克隆的是Money对象，所以强转为Money对象
        //将克隆后的对象地址传给student3引用所指向的对象中的m引用
        student3.m = (Money) this.m.clone();//通过this.m调用clone方法，现在需要克隆的是student对象中m引用所指向的对象，所以this代表的就是student引用
        return student3;//这里是将克隆后用来接收克隆结果的student3作为返回结果返回，所以return将克隆的值给了student2

        // return super.clone();
    }
}
public class Test {
    public static void main(String[] args) {
        Student student = new Student();
        System.out.println(student);
    }
    public static void main1(String[] args) throws CloneNotSupportedException {
        Student student = new Student();
        Student student2 =(Student)student.clone();//student2接收了返回的克隆结果
        System.out.println(student.m.money);
        System.out.println(student2.m.money);
        System.out.println("=============");
        student2.m.money = 99;
        System.out.println(student.m.money);
        System.out.println(student2.m.money);




    }
}
